package org.polaris.gift.service.impl;

import cn.hutool.core.util.StrUtil;
import org.polaris.gift.constants.ResponseCode;
import org.polaris.gift.constants.UserConstants;
import org.polaris.gift.exception.BusinessException;
import org.polaris.gift.service.IVerifyCodeService;
import org.polaris.gift.util.AjaxResult;
import org.polaris.gift.util.SmsUtil;
import org.polaris.gift.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public AjaxResult sendRegisterVerifyCode(String phone) {
        // 1 参数校验
        // 1.1 参数非空校验
        String redisKey = UserConstants.REGISTER_SEND_SMS_VERIFY_CODE_KEY +phone;
        // 2 判断该手机号在redis中有没有验证码
        Object smsCodeByRedis = redisTemplate.opsForValue().get(redisKey);
        String smsCode = "";
        if(Objects.nonNull(smsCodeByRedis)){
            String smsCodeStr = smsCodeByRedis.toString();      // 验证码:发送时间
            smsCode = smsCodeStr.split(":")[0];
            String sendTime = smsCodeStr.split(":")[1];
            // 2.1 如果有,判断是否过了重发时间
            if(System.currentTimeMillis() - Long.parseLong(sendTime) <= 60*1000){
                // 2.1.1 如果没有过重发时间,返回错误信息
                throw new BusinessException(ResponseCode.RESPONSE_CODE_400007
                        .getMessage(), ResponseCode.RESPONSE_CODE_400007.getCode());
            }
        }else{
            // 2.2 如果手机验证码不存在
            // 2.2.1 重新生成随机字符串作为验证码
            smsCode = VerifyCodeUtils.generateVerifyCode(6);
        }
        // 2.2.2 将验证码存入redis中,并设置过期时间和重发时间
        String value = smsCode+":"+System.currentTimeMillis();
        redisTemplate.opsForValue().set(redisKey,value,5, TimeUnit.MINUTES);

        // 2.2.3 调用短信发送接口发送短信
        String msg = "你的注册验证码是%s,请在5分钟以内使用!";
        SmsUtil.sendSms(phone,String.format(msg,smsCode));
        System.out.println(String.format(msg,smsCode));
        return AjaxResult.me();
    }

    @Override
    public String getRegisterVerifyCode(String phone) {
        // 1.1 参数非空校验
        String redisKey = UserConstants.REGISTER_SEND_SMS_VERIFY_CODE_KEY +phone;
        // 2 判断该手机号在redis中有没有验证码
        String smsCodeByRedis = (String) redisTemplate.opsForValue().get(redisKey);
        if (StrUtil.isBlank(smsCodeByRedis))
            return "";
        return smsCodeByRedis.split(":")[0];
    }

    @Override
    public AjaxResult sendFindPwdVerifyCode(String phone) {
        return null;
    }

    @Override
    public String getFindPwdVerifyCode(String phone) {
        return null;
    }
}

